package com.spring.app.common.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spring.app.common.dao.UserDAO;
import com.spring.app.common.domain.DBUser;


@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

	private UserDAO userDAO ;// = new UserDAO();
	  
	 public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}
    

	@SuppressWarnings("deprecation")
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
		 
	  UserDetails user = null;
	   
	  try {
	    
	   DBUser dbUser = userDAO.select(username);
	    
	   user = new User(dbUser.getUsername(), dbUser.getPassword().toLowerCase(), true, true, true, true,getAuthorities(dbUser.getAccess()));
		   
	 
	  } catch (Exception e) {
	 //  logger.error("Error in retrieving user");
	   throw new UsernameNotFoundException("Error in retrieving user");
	  }
	   
	  return user;
	 }
	  
	
	 public GrantedAuthority[] getAuthorities(Integer access) {
		 List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);
		 authList.add(new GrantedAuthorityImpl("ROLE_COMMON"));
		 if ( access.compareTo(1) == 0) {
		    authList.add(new GrantedAuthorityImpl("ROLE_PREMIUM"));
		 }
         return (GrantedAuthority[])authList.toArray(new GrantedAuthority[0]);
    }
	 


}
